<template>
  <el-dialog :visible.sync="dialogVisible" title="上传" width="500px">
    <div class="flex-box">
      <el-upload
        class="upload-demo"
        :on-success="successHandle"
        :before-upload="avatarBeforeUpload"
        drag
        action="/sys/storage/upload"
        multiple
        :headers="{ ACCESS_TOKEN: ACCESS_TOKEN }"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  data() {
    return {
      dialogVisible: false,
      ACCESS_TOKEN: ""
    };
  },
  mounted() {
    this.ACCESS_TOKEN = getToken();
  },
  methods: {
    successHandle(res, file, fileList) {
      console.log(res);
      this.$message(res.msg);
    },
    avatarBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 5;
      if (!isRightSize) {
        this.$message.error("文件大小超过 5MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      return isRightSize && isAccept;
    }
  },
  watch: {
    dialogVisible(val){
      this.$emit('initData')
    }
  }
};
</script>

<style>
.flex-box {
  display: flex;
  justify-content: center;
}
</style>
